<?php

use mip\ChinesePinyin;
use mip\Mip;

//function compress_html($higrid_uncompress_html_source)
//{
//    return compress2($higrid_uncompress_html_source);
//
//}

//function compress1($higrid_uncompress_html_source){
//    // 处理  script标签
/*    $custom = preg_split('/(<script.*?>.*?<\/script>)/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE);*/
//    $higrid_uncompress_html_source = '';
//    foreach ($custom as $k => $c1) {
//
//        if (strpos($c1, '<script') === 0) {
//            $c = preg_replace('/\\/\\/.*\\n/i', '', $c);
//            $c = preg_replace('/\\/\\*.*?\\*\\//msi', '', $c);
//            $c = str_replace(array("", "\r", "\n", "\t", '  ', '    ', '    '), '', $c);
//        }
//        $higrid_uncompress_html_source .= $c;
//    }
//
//    // 处理  style标签
/*    $custom = preg_split('/(<style.*?>.*?<\/style>)/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE);*/
//    $higrid_uncompress_html_source = '';
//    foreach ($custom as $k => $c) {
//        if (strpos($c, '<style') === 0) {
//            $c = preg_replace('/\\/\\*.*?\\*\\//msi', '', $c);
//            $c = str_replace(array("", "\r", "\n", "\t", '  ', '    ', '    '), '', $c);
//        }
//        $higrid_uncompress_html_source .= $c;
//    }
//
//    $chunks = preg_split('/(<pre.*?\/pre>)/ms', $higrid_uncompress_html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
//    $higrid_uncompress_html_source = '';
//    foreach ($chunks as $c) {
//        // 处理所有不是pre标签的内容
//        if (strpos($c, '<pre') !== 0) {
//            $c = preg_replace('/[\\n\\r\\t]+/', ' ', $c);
//
//            // 去掉html中的注释
//            $c = preg_replace('/(<!--.*?-->)/', '', $c);
//            $c = preg_replace('/ {2,}/', ' ', $c);
//            $c = preg_replace('/>\\s</', '><', $c);
//        }
//        $higrid_uncompress_html_source .= $c;
//    }
//    //
//    return $higrid_uncompress_html_source;
//}

//function compress2($html_source)
//{
//    $chunks   = preg_split('/(<pre.*?\/pre>|<textarea.*?\/textarea>|<script.*?\/script>)/msi', $html_source, -1, PREG_SPLIT_DELIM_CAPTURE);
//    $compress = '';
//    foreach ($chunks as $c) {
//        if (strtolower(substr($c, 0, 4)) == '<pre' || strtolower(substr($c, 0, 9)) == '<textarea') {
//            $compress .= $c;
//            continue;
//        } elseif (strtolower(substr($c, 0, 7)) == '<script' && strpos($c, '//') != false
//            && (strpos($c, "\r") !== false || strpos($c, "\n") !== false)) { // JS代码，包含“//”注释的，单行代码不处理
//            $tmps = preg_split('/(\r|\n)/ms', $c, -1, PREG_SPLIT_NO_EMPTY);
//            $c    = '';
//            foreach ($tmps as $tmp) {
//                if (strpos($tmp, '//') !== false) { // 对含有“//”的行做处理
//                    if (substr(trim($tmp), 0, 2) == '//') { // 开头是“//”的就是注释
//                        continue;
//                    }
//                    $chars   = preg_split('//', $tmp, -1, PREG_SPLIT_NO_EMPTY);
//                    $is_quot = $is_apos = false;
//                    foreach ($chars as $key => $char) {
//                        if ($char == '"' && !$is_apos && $key > 0 && $chars[$key - 1] != '\\') {
//                            $is_quot = !$is_quot;
//                        } elseif ($char == '\'' && !$is_quot && $key > 0 && $chars[$key - 1] != '\\') {
//                            $is_apos = !$is_apos;
//                        } elseif ($char == '/' && $chars[$key + 1] == '/' && !$is_quot && !$is_apos) {
//                            $tmp = substr($tmp, 0, $key); // 不是字符串内的就是注释
//                            break;
//                        }
//                    }
//                }
//                $c .= $tmp;
//            }
//        }
//
//        //$c        = preg_replace('/(?<!(com))(\\/\\*.*?\\*\\/)/msi', '', $c); // 清除 CSS & JS 的注释
//        $c        = preg_replace('/[\\n\\r\\t]+/', ' ', $c); // 清除换行符，清除制表符
//        $c        = preg_replace('/\\s{2,}/', ' ', $c); // 清除额外的空格
//        $c        = preg_replace('/>\\s</', '> <', $c); // 清除标签间的空格
//
//        $c        = preg_replace('/<!--[^!]*-->/', '', $c); // 清除 HTML 的注释
//        $compress .= $c;
//    }
//    return $compress;
//}

function create_salt($length = 12)
{
    return $salt = substr(uniqid(rand()), 0, $length);
}

function create_md5($string, $salt)
{
    return md5($string . $salt);
}

function uuid()
{
    $charid = strtolower(md5(uniqid(rand(), true)));
    return substr($charid, 0, 24);
}

function jsonError($message = '', $url = null)
{
    $return['msg'] = $message;
    $return['code'] = -1;
    $return['url'] = $url;
    return json($return, 200);
}

function jsonSuccess($message = '', $data = '', $url = null)
{
    $return['msg'] = $message;
    $return['data'] = $data;
    $return['code'] = 1;
    $return['url'] = $url;
    return json($return, 200);
}

function read_file_text($fullpath){
    if(file_exists($fullpath)) {
        $fp = fopen($fullpath, "r");
        $str = fread($fp, filesize($fullpath));//指定读取大小，这里把整个文件内容读取出来
        fclose($fp);

        return $str;
    }
    return false;
}

/**
 * 读取文件夹下的文件成列表
 * @param $dir
 * @param null $file_type
 * @return array|bool
 */
function fetch_file_lists($dir, $file_type = null)
{
    if ($file_type) {
        if (substr($file_type, 0, 1) == '.') {
            $file_type = substr($file_type, 1);
        }
    }

    $base_dir = realpath($dir);

    if (!file_exists($base_dir)) {
        return false;
    }

    $dir_handle = opendir($base_dir);

    $files_list = array();

    while (($file = readdir($dir_handle)) !== false) {
        if(substr($file, 0, 1) == '.'){
            continue;
        }
        if ( !is_dir($base_dir . DS . $file)) {
            if (($file_type AND end(explode('.', $file)) == $file_type) OR !$file_type) {
                $files_list[] = $base_dir . DS . $file;
            }
        } else if ( is_dir($base_dir . DS . $file)) {
            if ($sub_dir_lists = fetch_file_lists($base_dir . DS . $file, $file_type)) {
                $files_list = array_merge($files_list, $sub_dir_lists);
            }
        }
    }
    return $files_list;
}

function create_folder($basepath,$foldername){
    $basepath = realpath($basepath);

    if (!file_exists($basepath)) {
        return 2;
    }

    $fullpath = $basepath.'/'.$foldername;
    if (file_exists($fullpath)&& is_dir($fullpath)) {
        return 3;
    }

    mkdir($fullpath,0755,true);
    return 0;
}

function remove_file($path){
    //如果是目录则继续
    if(is_dir($path)){
        //扫描一个文件夹内的所有文件夹和文件并返回数组
        $p = scandir($path);
        foreach($p as $val){
            //排除目录中的.和..
            if($val !="." && $val !=".."){
                //如果是目录则递归子目录，继续操作
                if(is_dir($path.$val)){
                    //子目录中操作删除文件夹和文件
                    remove_file($path.$val.'/');
                    //目录清空后删除空文件夹
                    @rmdir($path.$val.'/');
                }else{
                    //如果是文件直接删除
                    unlink($path.$val);
                }
            }
        }
        @rmdir($path);
    }else{
        unlink($path);
    }
}


/**
 * 读取文件夹下的结构，成itree需要的结构。
 * @param $file_list
 */
function fetch_file_itree(&$arr, $dir, $rootdir , $fileIcon ){

    $base_dir = realpath($dir);

    if (!file_exists($base_dir)) {
        return false;
    }

    $dir_handle = opendir($base_dir);


    while (($file = readdir($dir_handle)) !== false) {
        if(substr($file, 0, 1) == '.'){
            continue;
        }

        $relative_path = str_replace($rootdir,'',$base_dir . DS . $file);

        if ( is_file($base_dir . DS . $file)) {
            $ext = substr($file,strripos($file,".")+1);
            $icon = $fileIcon[$ext];
            if($icon == null){
                $icon = $fileIcon['otherfile'];
            }
            $editable = $file=='template.json'?false : true;

            $arr[] = ['folder'=>2 , 'type'=>'file' , 'ext'=>$ext , 'editable'=>$editable , 'title'=> $file , 'icon'=>$icon , 'fullpath'=> $base_dir . DS . $file,'filename'=>$file,'path'=>$relative_path ];
        } else if ( is_dir($base_dir . DS . $file)) {
            $arr2 = ['folder'=>1, 'type'=>'folder', 'editable'=>true,  'title'=>$file, 'expand'=>false, 'icon'=>$fileIcon['folder'] , 'fullpath'=> $base_dir . DS . $file ,'filename'=>$file ,'path'=>$relative_path ,  'children'=>[] ];
            fetch_file_itree( $arr2['children'],$base_dir . DS . $file , $rootdir ,$fileIcon );
            $arr[] = $arr2;
        }else{
            continue;
        }

    }

    // 按照先文件夹后文件，再名称正序，排序
    $titles = [];
    $folders = [];
    foreach( $arr as $k=>$v ){
        $titles[$k] = $v['title'];
        $folders[$k] = $v['folder'];
    }

    array_multisort ($folders,SORT_ASC,$titles,SORT_ASC ,$arr );
    return $arr;
}

function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    $tree = [];
    if (is_array($list)) {
        $refer = [];
        // 将每个主键为key，组成新的数组结构
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $refer[$data[$pk]] =& $list[$key];
        }

        // 循环所有的元素，找到其父元素，然后放到父元素的子元素列表中
        foreach ($list as $key => $data) {
            if (!isset($list[$key][$child])) {
                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

function list_to_cascader($list,$pk = 'id', $pid = 'pid', $value_field='id' ,$label_field='title' , $child = '_child', $root = 0)
{
    $tree = [];
    if (is_array($list)) {
        $refer = [];
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $tmp = array();
            $tmp[$pid] = $list[$key][$pid];
            $tmp[$pk] = $list[$key][$pk];
            $tmp['value'] = $list[$key][$value_field];
            $tmp['label'] = $list[$key][$label_field];
            $list[$key] = $tmp;

            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            if (!isset($list[$key][$child])) {
                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

function formatTime($value)
{
    if (time() - $value < 60) {
        return (time() - $value) . '秒前';
    }
    if (time() - $value > 60 && time() - $value < 3600) {
        return (int)((time() - $value) / 60) . '分钟前';
    }
    if (time() - $value > 3600 && time() - $value < 86400) {
        return (int)((time() - $value) / 3600) . '小时前';
    }
    if (time() - $value > 86400 && time() - $value < 172800) {
        return '1天前';
    }
    return date('m-d', $value);
}

function getAvatarUrl($uid)
{
    if (MIP_HOST) {
        if (file_exists(ROOT_PATH . 'uploads' . DS . 'avatar' . DS . $uid . '.jpg')) {
            return '/uploads/avatar/' . $uid . '.jpg';
        } else {
            return '/public/assets/common/images/avatar.jpg';
        }
    } else {
        if (file_exists(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar' . DS . $uid . '.jpg')) {
            return '/uploads/avatar/' . $uid . '.jpg';
        } else {
            return '/assets/common/images/avatar.jpg';
        }
    }

}

function getFile($url, $save_dir = '', $filename = '', $type = 0)
{
    if (trim($url) == '') {
        return false;
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //创建保存目录
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return false;
    }
    //获取远程文件所采用的方法
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $content = ob_get_contents();
        ob_end_clean();
    }
    //echo $content;
    $size = strlen($content);
    //文件大小
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $content);
    fclose($fp2);
    unset($content, $url);
    return array(
        'file_name' => $filename,
        'save_path' => $save_dir . $filename,
        'file_size' => $size
    );
}

function addFileToZip($path, $zip)
{
    $handler = opendir($path);
    while (($filename = readdir($handler)) !== false) {
        if ($filename != "." && $filename != "..") {
            if (is_dir($path . "/" . $filename)) {
                addFileToZip($path . "/" . $filename, $zip);
            } else {
                $zip->addFile($path . "/" . $filename);
            }
        }
    }
    @closedir($path);
}

function pushData($api, $urls)
{
    $ch = curl_init();
    $options = array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    curl_close($ch);
    if ($result) {
        return $result;
    } else {
        return false;
    }
}

function getData($api, $postData = '')
{
    if (!$api) {
        return false;
    }
    if (empty($postData)) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);

        curl_close($ch);
    } else {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
    }
    if ($result) {
        return $result;
    } else {
        return null;
    }
}

function curlData($url)
{
    $header = array(
        //  "Host:www.baidu.com",
        "Content-Type:application/x-www-form-urlencoded",//post请求
        "Connection: keep-alive",
        'Referer:http://www.baidu.com',
        'User-Agent: Mozilla/5.0 (compatible; Baiduspider-render/2.0; +http://www.baidu.com/search/spider.html)'
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $html = curl_exec($ch);
    curl_close($ch);
    return $html;
}

function linkClient($url, $postData = '', $header = '')
{
    if (!$url) {
        return false;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $html = curl_exec($ch);
    curl_close($ch);
    return $html;
}

function getSHA1($strToken, $intTimeStamp, $strNonce, $strEncryptMsg = '')
{
    $arrParams = array(
        $strToken,
        $intTimeStamp,
        $strNonce,
    );
    if (!empty($strEncryptMsg)) {
        array_unshift($arrParams, $strEncryptMsg);
    }
    sort($arrParams, SORT_STRING);
    $strParam = implode($arrParams);
    return sha1($strParam);
}

function mipfilter($content)
{
    if (strpos($content, '{FlyBirdCSS}') !== false) {

        $cssContent = [];
//      $cssData = array(
//          'fontSize' => 'font-size',
//          'margin' => 'margin',
//          'mLeft' => 'margin-left',
//          'mRight' => 'margin-right',
//          'mTop' => 'margin-top',
//          'mBottom' => 'margin-bottom',
//          'padding' => 'padding',
//          'pLeft' => 'padding-left',
//          'pRight' => 'padding-right',
//          'pTop' => 'padding-top',
//          'pBottom' => 'padding-bottom',
//          'color' => 'color',
//          'bgColor' => 'background',
//          'width' => 'width',
//          'maxWidth' => 'max-width',
//          'minWidth' => 'min-width',
//          'height' => 'height',
//          'position' => 'position',
//          'top' => 'top',
//          'left' => 'left',
//          'right' => 'right',
//          'bottom' => 'bottom',
//          'border' => 'border',
//          'bRadius' => 'border-radius',
//          'display' => 'display',
//          'float' => 'float',
//          'overflow' => 'overflow',
//          'whiteSpace' => 'white-space'
//      );
//      preg_match_all("/class=.+?['|\"]/i", $content, $contentClassArray);
//      if ($contentClassArray) {
//          foreach ($contentClassArray[0] as $key => $value) {
//              preg_match_all('/{(.*?)}/', $value, $contentArray);
//              foreach ($contentArray[1] as $k => $v) {
//                  foreach ($cssData as $subK => $subV) {
//                      $className = $contentArray[1][$k];
//                      if (strpos($className, $subK) !== false) {
//                          $resCalssName = str_replace('%', '', $className);
//                          $resCalssName = str_replace('#', '', $resCalssName);
//                          if (!isset($cssContent['.'.$resCalssName])) {
//                              $cssContent['.'.$resCalssName] = $subV . ':'.str_replace($subK, '', $className).'!important;';
//                          }
//                          $content = str_replace($contentArray[0][$k], $resCalssName, $content);
//                      }
//                  }
//              }
//          }
//      }
        $tempCssContent = '';
        if ($cssContent) {
            foreach ($cssContent as $key => $value) {
                $tempCssContent .= $key . '{' . $value . '}';
            }
        }
        preg_match_all("/<[a-z]{1,}\s+.*?>/", $content, $contentHtmlArray);
        if ($contentHtmlArray) {
            foreach ($contentHtmlArray[0] as $key => $value) {
                if (strpos($value, 'style=') !== false) {
                    preg_match_all("/style=[\'|\"](.*?)[\'|\"]/i", $value, $contentcssArray);
                    if ($contentcssArray) {
                        $cssName = 'mipmb-css-' . $key;
                        if (strpos($value, 'class=') !== false) {
                            preg_match_all("/class=[\'|\"](.*?)[\'|\"]/i", $value, $subClassArray);
                            if ($subClassArray && $subClassArray[1]) {
                                $tempClassName = $subClassArray[1];
                                $className = 'class="' . $tempClassName[0] . ($tempClassName[0] ? ' ' : '') . $cssName . '"';
                                $contentHtmlArray[0][$key] = str_replace($subClassArray[0][0], $className, $contentHtmlArray[0][$key]);
                                $cssBlock = '.' . $cssName . '{' . $contentcssArray[1][0] . '}';
                                $tempCssContent .= $cssBlock;
                                $contentHtmlArray[0][$key] = str_replace($contentcssArray[0][0], '', $contentHtmlArray[0][$key]);
                            }
                        } else {
                            $className = 'class="' . $cssName . '"';
                            $cssBlock = '.' . $cssName . '{' . $contentcssArray[1][0] . '}';
                            $tempCssContent .= $cssBlock;
                            $contentHtmlArray[0][$key] = str_replace($contentcssArray[0][0], $className, $contentHtmlArray[0][$key]);
                        }
                        $content = str_replace($value, $contentHtmlArray[0][$key], $content);
                    }


                }
            }
        }

        preg_match_all("/<style type=\"text\/css\">(.*?)<\/style>/is", $content, $contentStyleTextArray);
        if ($contentStyleTextArray) {
            foreach ($contentStyleTextArray[1] as $key => $value) {
                $tempCssContent .= $value;
                $content = str_replace($contentStyleTextArray[0][0], '', $content);
            }
        }
        preg_match_all("/<style>(.*?)<\/style>/is", $content, $contentStyleArray);
        if ($contentStyleArray) {
            foreach ($contentStyleArray[1] as $key => $value) {
                $tempCssContent .= $value;
                $content = str_replace($contentStyleArray[0][0], '', $content);
            }
        }

        $content = str_replace('{FlyBirdCSS}', $tempCssContent, $content);
    }
    return $content;
}

function formatUrl($srcurl, $baseurl)
{
    $srcinfo = parse_url($srcurl);
    if (isset($srcinfo['scheme'])) {
        return $srcurl;
    }
    $baseinfo = parse_url($baseurl);
    $url = $baseinfo['scheme'] . '://' . $baseinfo['host'];
    if (substr($srcinfo['path'], 0, 1) == '/') {
        $path = $srcinfo['path'];
    } else {
        $path = dirname($baseinfo['path']) . '/' . $srcinfo['path'];
    }
    $rst = array();
    $path_array = explode('/', $path);
    if (!$path_array[0]) {
        $rst[] = '';
    }
    foreach ($path_array AS $key => $dir) {
        if ($dir == '..') {
            if (end($rst) == '..') {
                $rst[] = '..';
            } elseif (!array_pop($rst)) {
                $rst[] = '..';
            }
        } elseif ($dir && $dir != '.') {
            $rst[] = $dir;
        }
    }
    if (!end($path_array)) {
        $rst[] = '';
    }
    $url .= implode('/', $rst);
    return str_replace('\\', '/', $url);
}

function gbkToUTF8($html)
{
    $arr = array("UTF-8", "ASCII", "GBK", "GB2312", "gb2312", "BIG5", "JIS", "eucjp-win", "sjis-win", "EUC-JP");
    $encode = mb_detect_encoding($html, $arr);
    $html = mb_convert_encoding(trim($html), "UTF-8", $encode);
    $html = str_replace('charset=GB2312', 'charset=UTF-8', $html);
    $html = str_replace('charset="GB2312"', 'charset="UTF-8"', $html);
    $html = str_replace("charset='GB2312'", "charset='UTF-8'", $html);
    $html = str_replace('charset=gb2312', 'charset=UTF-8', $html);
    $html = str_replace('charset="gb2312"', 'charset="UTF-8"', $html);
    $html = str_replace("charset='gb2312'", "charset='UTF-8'", $html);
    $html = str_replace('charset=GBK', 'charset=UTF-8', $html);
    $html = str_replace('charset="GBK"', 'charset="UTF-8"', $html);
    $html = str_replace("charset='GBK'", "charset='UTF-8'", $html);
    $html = str_replace('charset=gbk', 'charset=UTF-8', $html);
    $html = str_replace('charset="gbk"', 'charset="UTF-8"', $html);
    $html = str_replace("charset='gbk'", "charset='UTF-8'", $html);
    $html = str_replace("charset=UTF-8", "", $html);
    return $html;
}


function getImage($url, $save_dir, $filename = '', $type = 0)
{
    if (!$url) {
        return false;
    }
    if (!$save_dir) {
        return false;
    }
    $ext = strrchr($url, '.');
    if ($ext != '.gif' || $ext != '.jpg' || $ext != '.png' || $ext != '.jpeg') {
        $ext = '.jpg';
    }

    $filename = uuid() . $ext;
    if (0 !== strrpos($save_dir, DS)) {
        $save_dir .= DS;
    }
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {
        return array('file_name' => '', 'save_path' => '', 'error' => 5);
    }
    if ($type) {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    } else {
//      ob_start();  
//      readfile($url);  
//      $content = ob_get_contents();  
//      ob_end_clean();  
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $content = curl_exec($ch);
        curl_close($ch);
    }
    //echo $content;  
    $size = strlen($content);
    //文件大小  
    $fp2 = @fopen($save_dir . $filename, 'a');
    fwrite($fp2, $content);
    fclose($fp2);
    unset($content, $url);

    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}

if (is_file(APP_PATH . 'function.php')) {
    include APP_PATH . 'function.php';
}


function getPinyin($name)
{
    if (!$name) {
        return false;
    }
    $Pinyin = new ChinesePinyin();
    $result = $Pinyin->TransformWithoutTone($name);
    return $result;
}

/**
 * 将content长字符串转换为支持MIP的格式
 * @param $content
 * @return string|string[]|null
 */
function convertContentForMip($content)
{
    $itemInfo['content'] = $content;


    $newhtml='';

    // 修改style为class
    $arr1 = preg_split('/(style=\".*?\")/', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
    foreach ($arr1 as $key => $val) {

        $fspos = strpos($val, 'style');
        if ($fspos !== 0) {
            $newhtml .= $val;
            continue;
        }
        preg_match('/style="(.*?)"/', $val, $style);

        if ($style[1] === '') {
            $newhtml .= $val;
            continue;
        }

        $cls = '';

        // 处理fb-code-bg-efefef
        $fspos = strpos($style[1], 'background-color:#efefef');
        if($fspos !== false ){
            $cls.='fb-code-bg-efefef ';
        }
        // 处理fb-code-color-000080
        $fspos = strpos($style[1], 'color:#000080');
        if($fspos !== false ){
            $cls.='fb-code-color-000080 ';
        }
        // 处理fb-code-color-808080
        $fspos = strpos($style[1], 'color:#808080');
        if($fspos !== false ){
            $cls.='fb-code-color-808080 ';
        }
        // 处理fb-code-color-0000ff
        $fspos = strpos($style[1], 'color:#0000ff');
        if($fspos !== false ){
            $cls.='fb-code-color-0000ff ';
        }
        // 处理fb-code-color-660e7a
        $fspos = strpos($style[1], 'color:#660e7a');
        if($fspos !== false ){
            $cls.='fb-code-color-660e7a ';
        }
        // 处理fb-code-color-008000
        $fspos = strpos($style[1], 'color:#008000');
        if($fspos !== false ){
            $cls.='fb-code-color-008000 ';
        }
        // 处理fb-code-color-7a7a43
        $fspos = strpos($style[1], 'color:#7a7a43');
        if($fspos !== false ){
            $cls.='fb-code-color-7a7a43 ';
        }
        // 处理fb-code-bold
        $fspos = strpos($style[1], 'font-weight:bold');
        if($fspos !== false ){
            $cls.='fb-code-bold ';
        }
        // 处理fb-code-italic
        $fspos = strpos($style[1], 'font-style:italic');
        if($fspos !== false ){
            $cls.='fb-code-italic ';
        }

        // 处理font-size
        $fspos = strpos($style[1], 'font-size');
        if ($fspos !== false) {
            $fs = substr($style[1], $fspos + strlen('font-size: '), 4);
            switch ($fs) {
                case '1.5e':
                    $cls .= 'fs-xlarge ';
                    break;
                case '1.25':
                    $cls .= 'fs-large ';
                    break;
                case '0.75':
                    $cls .= 'fs-small ';
                    break;
                case '0.5e':
                    $cls .= 'fs-xsmall ';
                    break;
            }
        }

        $fspos = strpos($style[1], 'color: rgb');
        if ($fspos !== false) {
            if (strpos($style[1], 'rgb(') !== false) {

                $fspos2 = strpos($style[1], ')');
                $fs = substr($style[1], $fspos + strlen('color: '), $fspos2 - $fspos - strlen('color: ') + 1);
                $fs = str_replace("rgb(", '', $fs);
                $fs = str_replace(")", '', $fs);
                $fs = str_replace(", ", '_', $fs);

                $cls .= 'color-' . $fs;
            }
        }

        $newstr = 'class="' . $cls . '" ' ;
        $newhtml .= $newstr;
    }

    $itemInfo['content'] =  preg_replace("/style=\".*?\"/i",'', $newhtml);

    preg_match_all('/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/', $itemInfo['content'], $imagesArray);
    $patern = '/^^((https|http|ftp)?:?\/\/)[^\s]+$/';
    foreach($imagesArray[0] as $key => $val) {
        @preg_match("/alt=[\'|\"](.*?)[\'|\"]/",$val,$tempAlt);
        if ($tempAlt) {
            $alt = $tempAlt[1];
        }
//        @preg_match("/width=[\'|\"](.*?)[\'|\"]/",$val,$tempWidth);
//        @preg_match("/height=[\'|\"](.*?)[\'|\"]/",$val,$tempHeight);
        $src = $imagesArray[1][$key];
        if (@preg_match($patern,$src)) {
            $src = $src;
        } else {
            if (strpos($src,';base64,') === false) {
                $src = config('domain') . $src;
            }
        }
        $tempImg = '<mip-img class="article-img" alt="'.$alt.'" src="'.$src.'" popup></mip-img>';
        $itemInfo['content'] =  str_replace($val,$tempImg,$itemInfo['content']);
    }

    @preg_match_all('/<iframe.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>*<\/iframe>/', $itemInfo['content'], $iframeArray);
    if ($iframeArray) {
        foreach($iframeArray[0] as $key => $val) {
            $layout = 'layout="responsive"';
            $tempiframe = '<mip-iframe   width="320" height="200" '.$layout.' src="'.$iframeArray[1][$key].'"></mip-iframe>';
            $itemInfo['content'] =  str_replace($val,$tempiframe,$itemInfo['content']);
        }
    }
    @preg_match_all('/<embed.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/', $itemInfo['content'], $embedArray);
    if ($embedArray) {
        foreach($embedArray[0] as $key => $val) {
            $layout = '';
            $tempembed = '<mip-embed type="ad-comm" '.$layout.' src="'.$embedArray[1][$key].'"></mip-embed>';
            $itemInfo['content'] =  str_replace($val,$tempembed,$itemInfo['content']);
        }
    }
    @preg_match_all('/<video.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>*<\/video>/', $itemInfo['content'], $videoArray);
    if ($videoArray) {
        foreach($videoArray[0] as $key => $val) {
            $layout = '';
            $tempvideo = '<mip-video '.$layout.' src="'.$videoArray[1][$key].'"></mip-video>';
            $itemInfo['content'] =  str_replace($val,$tempvideo,$itemInfo['content']);
        }
    }
    return $itemInfo['content'];
}

/**
 * 从content长字符串中获取 Img地址
 * @param $content
 */
function getImgsFromContent($content){

    $patern = '/^^((https|http|ftp)?:?\/\/)[^\s]+$/';
    $srcimgs = [];
    $fullimgs = [];
    if (preg_match_all('/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/', $content, $imgs)) {

        foreach ($imgs[1] as $key => $value) {
            $srcimgs[$key] = $value;
            if (@preg_match($patern, $value)) {
                $fullimgs[$key] = $value;
            } else {
                $fullimgs[$key] = config('mipInfo')['domain'] . $value;
            }
        }

    }

    return [$srcimgs,$fullimgs];
}

/**
 * 获取文章中包含关键字的段落
 * @param $content
 * @param $keyword
 */
function getChapterByKeyword($content,$keyword){
    if(empty($content)||empty($keyword)){
        return false;
    }

    if(strpos("&lt;",$content)!==false){
        $content = htmlspecialchars_decode($content);
    }

    $arr = preg_split("/(\\n)/",$content);

    $arr1 = [];
    foreach ($arr as $k=>$v){
        if(strpos($v,$keyword)!== false){
            $arr1[] = $v;
        }
    }
    return $arr1;
}

/**
 * 替换富文本编辑器中的换行，为普通字符串
 * @param $html
 */
function decodeHtmlForRichEditor($html){

    $str=str_replace('</p>',"\n",$html);
    $str=preg_replace('/<.*?>/',"",$str);
    $str=str_replace('&nbsp;'," ",$str);
    return $str;
}

function encodeHtml($longText){

    $str = str_replace("\n","<br>",$longText);
    return $str;
}

function getReadSeconds($wordCount,$imgCount){
    $wordSeconds = ceil($wordCount/5);
    if($imgCount<10) {
        $imgSecondes = (12 + 12 - ($imgCount - 1)) / 2 * $imgCount;
    }else{
        $imgSecondes = (12 + 12 - (10 - 1)) / 2 * 10 + 3*$imgCount - 10 ;
    }
    return $wordSeconds+$imgSecondes;
}

/**
 * 以后再用
 * @param $dirty_html
 * @return string
 */
function htmlp($dirty_html){
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    return $purifier->purify($dirty_html);
}



